<template>
  <div id="homePage">
    <!-- 主容器 -->
    <div class="main-container">
      <!-- 英雄区域 -->
      <div class="hero-section">
        <h1 class="hero-title">
          <span class="gradient-text">AI代码生成平台</span>
        </h1>
        <p class="hero-subtitle">让AI帮您快速构建应用，从想法到实现只需几分钟</p>

        <!-- 用户输入区域 -->
        <div class="user-prompt-section">
          <div class="prompt-container">
            <!-- 打字机效果文本 -->
            <div
              ref="demoTextRef"
              class="demo-text"
              :style="{
                opacity: userPrompt ? 0 : 1,
                pointerEvents: 'none'
              }"
            ></div>

            <!-- 实际输入区域 -->
            <a-textarea
              v-model:value="userPrompt"
              placeholder="请描述您想要创建的应用..."
              :rows="8"
              class="user-input"
              @focus="handleInputFocus"
              @blur="handleInputBlur"
            />

            <!-- 光标效果 -->
            <div
              ref="cursorRef"
              class="typing-cursor"
              :style="{
                opacity: showCursor && !userPrompt ? 1 : 0
              }"
            ></div>
          </div>

          <!-- 快捷操作按钮 -->
          <div class="quick-actions">
            <a-button
              type="primary"
              size="large"
              :loading="creating"
              @click="createApp"
              :disabled="!userPrompt.trim()"
            >
              开始创建
            </a-button>
            <a-button size="large" ghost>
              查看示例
            </a-button>
          </div>
        </div>

        <!-- 对话历史卡片 -->
        <div v-if="chatHistories.length > 0" class="chat-history-section">
          <h3>最近对话</h3>
          <div class="chat-cards-container">
            <div
              v-for="chat in chatHistories.slice(0, 6)"
              :key="chat.id"
              class="chat-card"
              @click="handleChatCardClick(chat)"
            >
              <div class="chat-card-cover">
                <img
                  :src="chat.appInfo?.cover || '/assets/default-cover.png'"
                  :alt="chat.appInfo?.appName || '应用封面'"
                  @error="handleImageError"
                />
              </div>
              <div class="chat-card-content">
                <div class="chat-title">{{ chat.appInfo?.appName || '未命名应用' }}</div>
                <div class="chat-message">{{ chat.message?.substring(0, 50) }}{{ chat.message && chat.message.length > 50 ? '...' : '' }}</div>
                <div class="chat-time">{{ formatChatTime(chat.createTime) }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="loadingChatHistory" class="loading-chat-history">
          <a-spin size="small" /> 加载对话历史中...
        </div>
      </div>
    </div>

    <!-- 白色内容容器 -->
    <div class="content-container">
      <!-- 我的作品区域 -->
      <div class="section my-works-section">
        <div class="section-header">
          <h2 class="section-title">我的作品</h2>
          <a-button type="link" @click="loadMyApps">查看更多</a-button>
        </div>
        <div class="apps-grid">
          <div v-if="myApps.loading" class="loading-container">
            <a-spin size="large" />
            <p>加载中...</p>
          </div>
          <div v-else-if="myApps.list.length === 0" class="empty-container">
            <a-empty description="暂无作品" />
          </div>
          <AppCard
            v-else
            v-for="app in myApps.list"
            :key="app.id"
            :app="app"
            :show-author="false"
            @view-chat="viewChat"
            @view-work="viewWork"
          />
        </div>
        <div v-if="myApps.list.length > 0" class="pagination-container">
          <a-pagination
            v-model:current="myApps.pagination.current"
            v-model:page-size="myApps.pagination.pageSize"
            :total="myApps.pagination.total"
            :show-size-changer="false"
            :show-quick-jumper="true"
            @change="loadMyApps"
          />
        </div>
      </div>

      <!-- 精选案例区域 -->
      <div class="section featured-section">
        <div class="section-header">
          <h2 class="section-title">精选案例</h2>
          <a-button type="link" @click="loadFeaturedApps">查看更多</a-button>
        </div>
        <div class="apps-grid">
          <div v-if="featuredApps.loading" class="loading-container">
            <a-spin size="large" />
            <p>加载中...</p>
          </div>
          <div v-else-if="featuredApps.list.length === 0" class="empty-container">
            <a-empty description="暂无精选案例" />
          </div>
          <AppCard
            v-else
            v-for="app in featuredApps.list"
            :key="app.id"
            :app="app"
            :show-author="true"
            :is-featured="true"
            @view-chat="viewChat"
            @view-work="viewWork"
          />
        </div>
        <div v-if="featuredApps.list.length > 0" class="pagination-container">
          <a-pagination
            v-model:current="featuredApps.pagination.current"
            v-model:page-size="featuredApps.pagination.pageSize"
            :total="featuredApps.pagination.total"
            :show-size-changer="false"
            :show-quick-jumper="true"
            @change="loadFeaturedApps"
          />
        </div>
      </div>
    </div>

    <!-- 鼠标跟随光效 -->
    <div ref="lightEffectRef" class="mouse-light-effect"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { useLoginUserStore } from '@/stores/loginUser'
import { listMyAppVoByPage, listGoodAppVoByPage, addApp, getAppVoById } from '@/api/appController'
import { listAppChatHistory } from '@/api/chatHistoryController'
import AppCard from '@/components/AppCard.vue'

const router = useRouter()
const loginUserStore = useLoginUserStore()

// 用户输入
const userPrompt = ref('')
const creating = ref(false)

// 打字机效果相关
const demoTextRef = ref<HTMLElement>()
const cursorRef = ref<HTMLElement>()
const showCursor = ref(true)
const demoText = '请帮我生成一个简单的个人博客...'
let typeTimer: NodeJS.Timeout | null = null
let deleteTimer: NodeJS.Timeout | null = null
let cursorTimer: NodeJS.Timeout | null = null
let currentIndex = 0
let isTyping = true

// 对话历史相关
const chatHistories = ref<(API.ChatHistory & { appInfo?: API.AppVO })[]>([])
const loadingChatHistory = ref(false)

// 我的作品数据
const myApps = ref({
  list: [] as API.AppVO[],
  loading: false,
  pagination: {
    current: 1,
    pageSize: 8,
    total: 0
  }
})

// 精选案例数据
const featuredApps = ref({
  list: [] as API.AppVO[],
  loading: false,
  pagination: {
    current: 1,
    pageSize: 8,
    total: 0
  }
})

// 鼠标光效
const lightEffectRef = ref<HTMLElement>()

// 打字机效果函数
const startTypewriter = () => {
  if (!demoTextRef.value) return

  const typeText = () => {
    if (currentIndex < demoText.length && isTyping) {
      demoTextRef.value!.textContent = demoText.substring(0, currentIndex + 1)
      currentIndex++
      typeTimer = setTimeout(typeText, 100)
    } else if (isTyping) {
      // 打字完成，等待2秒后开始删除
      setTimeout(() => {
        isTyping = false
        deleteText()
      }, 2000)
    }
  }

  const deleteText = () => {
    if (currentIndex > 0 && !isTyping) {
      demoTextRef.value!.textContent = demoText.substring(0, currentIndex - 1)
      currentIndex--
      deleteTimer = setTimeout(deleteText, 50)
    } else if (!isTyping) {
      // 删除完成，重新开始打字
      isTyping = true
      setTimeout(typeText, 1000)
    }
  }

  typeText()
}

// 光标闪烁效果
const startCursorBlink = () => {
  cursorTimer = setInterval(() => {
    showCursor.value = !showCursor.value
  }, 500)
}

// 清除所有定时器
const clearTimers = () => {
  if (typeTimer) {
    clearTimeout(typeTimer)
    typeTimer = null
  }
  if (deleteTimer) {
    clearTimeout(deleteTimer)
    deleteTimer = null
  }
  if (cursorTimer) {
    clearInterval(cursorTimer)
    cursorTimer = null
  }
}

// 输入框焦点事件
const handleInputFocus = () => {
  clearTimers()
  if (demoTextRef.value) {
    demoTextRef.value.textContent = ''
  }
  showCursor.value = false
}

const handleInputBlur = () => {
  if (!userPrompt.value.trim()) {
    currentIndex = 0
    isTyping = true
    startTypewriter()
    startCursorBlink()
  }
}

// 实时同步输入内容到demoText
watch(userPrompt, (newValue) => {
  if (demoTextRef.value && newValue) {
    demoTextRef.value.textContent = newValue
  }
})

// 创建应用
const createApp = async () => {
  if (!userPrompt.value.trim()) {
    message.warning('请输入应用描述')
    return
  }

  if (!loginUserStore.loginUser?.id) {
    message.warning('请先登录')
    router.push('/user/login')
    return
  }

  creating.value = true
  try {
    const res = await addApp({
      initPrompt: userPrompt.value.trim()
    })

    if (res.data.code === 0 && res.data.data) {
      message.success('应用创建成功')
      // 跳转到对话页面
      router.push(`/app/chat/${res.data.data}`)
    } else {
      message.error(res.data.message || '创建失败')
    }
  } catch (error) {
    console.error('创建应用失败:', error)
    message.error('创建应用失败')
  } finally {
    creating.value = false
  }
}

// 加载我的作品
const loadMyApps = async (page = 1) => {
  if (!loginUserStore.loginUser?.id) return

  myApps.value.loading = true
  try {
    const res = await listMyAppVoByPage({
      pageNum: page,
      pageSize: myApps.value.pagination.pageSize
    })

    if (res.data.code === 0 && res.data.data) {
      myApps.value.list = res.data.data.records || []
      myApps.value.pagination.current = page
      myApps.value.pagination.total = res.data.data.totalRow || 0
    }
  } catch (error) {
    console.error('加载我的作品失败:', error)
    message.error('加载我的作品失败')
  } finally {
    myApps.value.loading = false
  }
}

// 加载精选案例
const loadFeaturedApps = async (page = 1) => {
  featuredApps.value.loading = true
  try {
    const res = await listGoodAppVoByPage({
      pageNum: page,
      pageSize: featuredApps.value.pagination.pageSize
    })

    if (res.data.code === 0 && res.data.data) {
      featuredApps.value.list = res.data.data.records || []
      featuredApps.value.pagination.current = page
      featuredApps.value.pagination.total = res.data.data.totalRow || 0
    }
  } catch (error) {
    console.error('加载精选案例失败:', error)
    message.error('加载精选案例失败')
  } finally {
    featuredApps.value.loading = false
  }
}

// 获取对话历史列表
const loadChatHistories = async () => {
  if (!loginUserStore.loginUser?.id) return

  loadingChatHistory.value = true
  try {
    // 获取用户的所有应用
    const myAppsRes = await listMyAppVoByPage({ pageNum: 1, pageSize: 100 })
    if (myAppsRes.data.code === 0 && myAppsRes.data.data?.records) {
      const allChatHistories: (API.ChatHistory & { appInfo?: API.AppVO })[] = []

      // 为每个应用获取对话历史
      for (const app of myAppsRes.data.data.records) {
        if (app.id) {
          try {
            const chatRes = await listAppChatHistory({
              appId: app.id,
              pageSize: 10
            })
            if (chatRes.data.code === 0 && chatRes.data.data?.records) {
              // 为每条对话历史添加应用信息
              const histories = chatRes.data.data.records.map(chat => ({
                ...chat,
                appInfo: app
              }))
              allChatHistories.push(...histories)
            }
          } catch (error) {
            console.error(`获取应用 ${app.id} 对话历史失败:`, error)
          }
        }
      }

      // 按创建时间倒序排列
      chatHistories.value = allChatHistories.sort((a, b) =>
        new Date(b.createTime || '').getTime() - new Date(a.createTime || '').getTime()
      )
    }
  } catch (error) {
    console.error('获取对话历史失败:', error)
    message.error('获取对话历史失败')
  } finally {
    loadingChatHistory.value = false
  }
}

// 处理封面图片加载失败
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.src = '/assets/default-cover.png'
}

// 点击对话卡片
const handleChatCardClick = (chat: API.ChatHistory & { appInfo?: API.AppVO }) => {
  // 清空当前输入文本
  userPrompt.value = ''

  // 清空demoText占位文本
  if (demoTextRef.value) {
    demoTextRef.value.textContent = ''
  }

  // 清除定时器
  clearTimers()

  // 跳转到对话页面
  if (chat.appId) {
    router.push(`/app/chat/${chat.appId}`)
  }
}

// 格式化时间显示
const formatChatTime = (timeStr?: string) => {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  const now = new Date()
  const diff = now.getTime() - date.getTime()

  if (diff < 60000) { // 1分钟内
    return '刚刚'
  } else if (diff < 3600000) { // 1小时内
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) { // 24小时内
    return `${Math.floor(diff / 3600000)}小时前`
  } else {
    return date.toLocaleDateString()
  }
}

// 查看对话
const viewChat = (appId: number) => {
  router.push(`/app/chat/${appId}`)
}

// 查看作品
const viewWork = (app: API.AppVO) => {
  if (!app.deployKey) {
    message.warning('应用尚未部署')
    return
  }

  const deployUrl = `${window.location.origin}/static/${app.deployKey}/`
  window.open(deployUrl, '_blank')
}

// 鼠标跟随光效
const handleMouseMove = (e: MouseEvent) => {
  if (!lightEffectRef.value) return

  const { clientX, clientY } = e
  lightEffectRef.value.style.left = `${clientX}px`
  lightEffectRef.value.style.top = `${clientY}px`
}

// 生命周期
onMounted(() => {
  loadMyApps()
  loadFeaturedApps()
  loadChatHistories()

  nextTick(() => {
    startTypewriter()
    startCursorBlink()
  })

  // 添加鼠标移动事件
  document.addEventListener('mousemove', handleMouseMove)
})

onUnmounted(() => {
  clearTimers()
  document.removeEventListener('mousemove', handleMouseMove)
})
</script>

<style scoped>
#homePage {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow-x: hidden;
}

/* 科技感网格背景 */
#homePage::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image:
    linear-gradient(rgba(255, 255, 255, 0.1) 1px, transparent 1px),
    linear-gradient(90deg, rgba(255, 255, 255, 0.1) 1px, transparent 1px);
  background-size: 50px 50px;
  pointer-events: none;
  z-index: 1;
}

.main-container {
  position: relative;
  z-index: 2;
  max-width: 1200px;
  margin: 0 auto;
  padding: 60px 24px;
}

.hero-section {
  text-align: center;
  margin-bottom: 80px;
}

.hero-title {
  font-size: 3.5rem;
  font-weight: 700;
  margin-bottom: 24px;
  line-height: 1.2;
}

.gradient-text {
  background: linear-gradient(135deg, #ffffff 0%, #f0f9ff 50%, #e0f2fe 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  text-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.hero-subtitle {
  font-size: 1.25rem;
  color: rgba(255, 255, 255, 0.9);
  margin-bottom: 48px;
  max-width: 600px;
  margin-left: auto;
  margin-right: auto;
  line-height: 1.6;
}

.user-prompt-section {
  max-width: 800px;
  margin: 0 auto;
}

.prompt-container {
  position: relative;
  margin-bottom: 32px;
}

.demo-text {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 12px 16px;
  color: #52c41a;
  font-size: 16px;
  line-height: 1.5;
  border: 2px solid transparent;
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  z-index: 1;
  white-space: pre-wrap;
  word-wrap: break-word;
  transition: opacity 0.3s ease;
}

.user-input {
  position: relative;
  z-index: 2;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border: 2px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  font-size: 16px;
  transition: all 0.3s ease;
}

.user-input:focus {
  border-color: #52c41a;
  box-shadow: 0 0 0 4px rgba(82, 196, 26, 0.1);
  background: rgba(255, 255, 255, 1);
}

.typing-cursor {
  position: absolute;
  width: 2px;
  height: 20px;
  background: #52c41a;
  z-index: 3;
  transition: opacity 0.3s ease;
}

.quick-actions {
  display: flex;
  gap: 16px;
  justify-content: center;
  margin-bottom: 48px;
}

.quick-actions .ant-btn {
  height: 48px;
  padding: 0 32px;
  font-size: 16px;
  border-radius: 24px;
  font-weight: 500;
}

.quick-actions .ant-btn-primary {
  background: linear-gradient(135deg, #52c41a 0%, #73d13d 100%);
  border: none;
  box-shadow: 0 4px 16px rgba(82, 196, 26, 0.3);
}

.quick-actions .ant-btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(82, 196, 26, 0.4);
}

.chat-history-section {
  margin-top: 48px;
}

.chat-history-section h3 {
  color: white;
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 24px;
  text-align: left;
}

.chat-cards-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.chat-card {
  display: flex;
  padding: 20px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.chat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  border-color: #52c41a;
}

.chat-card-cover {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  overflow: hidden;
  flex-shrink: 0;
  margin-right: 16px;
}

.chat-card-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.chat-card-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.chat-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.chat-message {
  font-size: 14px;
  color: #6b7280;
  line-height: 1.4;
  margin-bottom: 12px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.chat-time {
  font-size: 12px;
  color: #9ca3af;
}

.loading-chat-history {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 32px;
  color: rgba(255, 255, 255, 0.8);
  font-size: 16px;
}

.loading-chat-history .anticon {
  margin-right: 12px;
}

.content-container {
  background: white;
  margin: 0 auto;
  max-width: 1200px;
  border-radius: 24px 24px 0 0;
  box-shadow: 0 -8px 32px rgba(0, 0, 0, 0.1);
  padding: 60px 40px;
  position: relative;
  z-index: 3;
}

.section {
  margin-bottom: 80px;
}

.section:last-child {
  margin-bottom: 0;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
}

.section-title {
  font-size: 2rem;
  font-weight: 700;
  color: #1f2937;
  margin: 0;
}

.apps-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.loading-container,
.empty-container {
  grid-column: 1 / -1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #6b7280;
}

.loading-container p,
.empty-container p {
  margin-top: 16px;
  font-size: 16px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 32px;
}

.mouse-light-effect {
  position: fixed;
  width: 300px;
  height: 300px;
  border-radius: 50%;
  background: radial-gradient(circle, rgba(82, 196, 26, 0.1) 0%, transparent 70%);
  pointer-events: none;
  transform: translate(-50%, -50%);
  z-index: 1;
  transition: opacity 0.3s ease;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-container {
    padding: 40px 16px;
  }

  .hero-title {
    font-size: 2.5rem;
  }

  .hero-subtitle {
    font-size: 1.1rem;
  }

  .content-container {
    padding: 40px 20px;
  }

  .section-title {
    font-size: 1.5rem;
  }

  .apps-grid {
    grid-template-columns: 1fr;
  }

  .chat-cards-container {
    grid-template-columns: 1fr;
  }

  .quick-actions {
    flex-direction: column;
    align-items: center;
  }

  .quick-actions .ant-btn {
    width: 200px;
  }
}

@media (max-width: 480px) {
  .hero-title {
    font-size: 2rem;
  }

  .content-container {
    border-radius: 16px 16px 0 0;
    padding: 32px 16px;
  }
}
</style>
